{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-01T07:47:11.073717Z",
     "start_time": "2018-09-01T07:46:54.050443Z"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using TensorFlow backend.\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import random as rn\n",
    "\n",
    "import os\n",
    "os.environ['PYTHONHASHSEED'] = '0'\n",
    "np.random.seed(42)\n",
    "rn.seed(12345)\n",
    "session_conf = tf.ConfigProto(device_count={\"CPU\": 4},intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)\n",
    "\n",
    "from keras import backend as K\n",
    "\n",
    "\n",
    "tf.set_random_seed(1234)\n",
    "sess = tf.Session(graph=tf.get_default_graph(), config=session_conf)\n",
    "K.set_session(sess)\n",
    "\n",
    "\n",
    "\n",
    "import pandas as pd\n",
    "\n",
    "import pickle\n",
    "from sklearn.model_selection import PredefinedSplit\n",
    "\n",
    "from keras.models import Sequential\n",
    "from keras.layers.core import Dense, Dropout, Activation\n",
    "\n",
    "from keras.layers.normalization import BatchNormalization\n",
    "from keras.optimizers import Adam\n",
    "from keras.callbacks import EarlyStopping\n",
    "from keras import regularizers\n",
    "from keras import initializers\n",
    "from sklearn.metrics import mean_squared_error\n",
    "Path = 'D:\\\\APViaML'\n",
    "from keras.callbacks import ModelCheckpoint\n",
    "from keras.models import load_model\n",
    "\n",
    "from hyperopt import fmin, tpe, hp, STATUS_OK, Trials\n",
    "pd.set_option('display.max_columns', 50)\n",
    "pd.set_option('display.max_rows', 100)\n",
    "pd.set_option('display.float_format', lambda x: '%.3f' % x)\n",
    "\n",
    "\n",
    "def get_demo_dict_data():\n",
    "    file = open(Path + '\\\\data\\\\alldata_demo_top1000.pkl','rb')\n",
    "    raw_data = pickle.load(file)\n",
    "    file.close()\n",
    "    return raw_data\n",
    "\n",
    "data = get_demo_dict_data()\n",
    "\n",
    "top_1000_data_X = data['X']\n",
    "top_1000_data_Y = data['Y']\n",
    "\n",
    "def creat_data(num,df_X=top_1000_data_X,df_Y=top_1000_data_Y):\n",
    "    '''\n",
    "    Data providing function:\n",
    "\n",
    "    This function is separated from model() so that hyperopt\n",
    "    won't reload data for each evaluation run.\n",
    "    '''\n",
    "    traindata_startyear_str = str(1958) \n",
    "    traindata_endyear_str = str(num + 1987) \n",
    "    vdata_startyear_str = str(num + 1976) \n",
    "    vdata_endyear_str = str(num + 1987) \n",
    "    testdata_startyear_str = str(num + 1988) \n",
    "  \n",
    "    X_traindata =  np.array(df_X.loc[traindata_startyear_str:traindata_endyear_str])\n",
    "    Y_traindata = np.array(df_Y.loc[traindata_startyear_str:traindata_endyear_str])\n",
    "    X_vdata = np.array(df_X.loc[vdata_startyear_str:vdata_endyear_str])\n",
    "    Y_vdata = np.array(df_Y.loc[vdata_startyear_str:vdata_endyear_str])\n",
    "    X_testdata = np.array(df_X.loc[testdata_startyear_str])\n",
    "    Y_testdata = np.array(df_Y.loc[testdata_startyear_str])\n",
    "        \n",
    "    return X_traindata, Y_traindata, X_vdata, Y_vdata, X_testdata, Y_testdata\n",
    "\n",
    "\n",
    "def Evaluation_fun(predict_array,real_array):\n",
    "    List1 = []\n",
    "    List2 = []\n",
    "    if len(predict_array) != len(real_array):\n",
    "        print('Something is worng!')\n",
    "    else:\n",
    "        for i in range(len(predict_array)):\n",
    "            List1.append(np.square(predict_array[i]-real_array[i]))\n",
    "            List2.append(np.square(real_array[i]))\n",
    "        result = round(100*(1 - sum(List1)/sum(List2)),3)\n",
    "    return result\n",
    "\n",
    "#define search space\n",
    "space = {'ll_float':hp.uniform('ll_float',0.01,0.2),\n",
    "         'lr': hp.loguniform('lr',np.log(0.005),np.log(0.2)),\n",
    "         'beta_1_float':hp.uniform('beta_1_float',0.8,0.95),\n",
    "         'beta_2_float':hp.uniform('beta_2_float',0.98,0.9999),\n",
    "         'epsilon_float':hp.uniform('epsilon_float',1e-09,1e-07), ##note\n",
    "         'batch_size': hp.quniform('batch_size',10,500,1),\n",
    "         'epochs': hp.quniform('epochs',20,50,1)\n",
    "         }"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-01T07:47:12.485973Z",
     "start_time": "2018-09-01T07:47:11.680832Z"
    }
   },
   "outputs": [],
   "source": [
    "X_traindata, Y_traindata, X_vdata, Y_vdata, X_testdata, Y_testdata = creat_data(num=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-01T07:47:55.365524Z",
     "start_time": "2018-09-01T07:47:55.355498Z"
    }
   },
   "outputs": [],
   "source": [
    "def f_NN1(params):\n",
    "    ## define params\n",
    "    ll_float= params[\"ll_float\"]#0.1\n",
    "    learn_rate_float= params[\"lr\"] #0.01\n",
    "    beta_1_float= params[\"beta_1_float\"] # 0.9\n",
    "    beta_2_float= params[\"beta_2_float\"] #0.999\n",
    "    epsilon_float= params[\"epsilon_float\"] #1e-08\n",
    "    batch_size_num = params['batch_size'] #\n",
    "    epochs_num = params['epochs'] #50\n",
    "\n",
    "    ## model structure\n",
    "    model_NN1 = Sequential()\n",
    "    init = initializers.RandomNormal(mean=0.0, stddev=0.05, seed=None)\n",
    "    model_NN1.add(Dense(32, input_dim =len(X_traindata[0]),\n",
    "                        kernel_initializer=init ,\n",
    "                        kernel_regularizer=regularizers.l1(ll_float)))\n",
    "    model_NN1.add(Activation(\"relu\"))\n",
    "    model_NN1.add(BatchNormalization())\n",
    "    model_NN1.add(Dense(1))\n",
    "\n",
    "    ## comile model\n",
    "    adam=Adam(lr=learn_rate_float, beta_1=beta_1_float, beta_2=beta_2_float, epsilon=epsilon_float)\n",
    "    model_NN1.compile(loss='mse', optimizer=adam,metrics=['mse'])\n",
    "\n",
    "    ## callback fun\n",
    "    early_stopping = EarlyStopping(monitor='val_loss', min_delta=0.0001, patience=2, verbose=0, mode='auto')\n",
    "    model_filepath = Path + '\\\\model\\\\NN1\\\\temp\\\\best_weights.h5'\n",
    "    checkpoint = ModelCheckpoint(filepath=model_filepath,save_weights_only=False,monitor='val_loss',mode='min' ,save_best_only='True')\n",
    "    callback_lists = [early_stopping,checkpoint]\n",
    "\n",
    "    ## fit model\n",
    "    model_NN1.fit(X_traindata, Y_traindata,\n",
    "              batch_size = int(batch_size_num) ,\n",
    "              epochs = int(epochs_num),\n",
    "              verbose = 0,\n",
    "              validation_data=(X_vdata, Y_vdata),\n",
    "              callbacks=callback_lists ,\n",
    "              shuffle=False)\n",
    "\n",
    "    ##get the best model\n",
    "    best_model = load_model(model_filepath)\n",
    "    # validate model\n",
    "    Y_pre_v = best_model.predict(X_vdata,verbose = 0)\n",
    "\n",
    "    Y_pre_vlist=[]\n",
    "    for x in Y_pre_v[:,0]:\n",
    "        Y_pre_vlist.append(x)\n",
    "\n",
    "    v_score = Evaluation_fun(Y_pre_vlist, Y_vdata)\n",
    "\n",
    "    ## prediction & save\n",
    "    Y_pre =best_model.predict(X_testdata,verbose = 1)\n",
    "\n",
    "    Y_pre_list=[]\n",
    "    for x in Y_pre[:,0]:\n",
    "        Y_pre_list.append(x)\n",
    "    test_score = Evaluation_fun(Y_pre_list, Y_testdata)\n",
    "   # print('Preformance:',v_score)\n",
    "    return {'loss': -v_score , 'status': STATUS_OK, \n",
    "            'y_pre_list':Y_pre_list,'test_score':test_score,\n",
    "            'models':best_model}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2018-09-01T07:47:55.715Z"
    },
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "1000/1000 [==============================] - 0s 25us/step\n",
      "1000/1000 [==============================] - 0s 42us/step\n",
      "1000/1000 [==============================] - 0s 37us/step\n",
      "1000/1000 [==============================] - 0s 42us/step\n",
      "1000/1000 [==============================] - 0s 46us/step\n",
      "1000/1000 [==============================] - 0s 38us/step\n",
      "1000/1000 [==============================] - 0s 46us/step\n",
      "1000/1000 [==============================] - 0s 58us/step\n",
      "1000/1000 [==============================] - 0s 45us/step\n",
      "1000/1000 [==============================] - 0s 51us/step\n",
      "1000/1000 [==============================] - 0s 54us/step\n",
      "1000/1000 [==============================] - 0s 61us/step\n",
      "1000/1000 [==============================] - 0s 64us/step\n",
      "1000/1000 [==============================] - 0s 52us/step\n",
      "1000/1000 [==============================] - 0s 75us/step\n",
      "1000/1000 [==============================] - 0s 63us/step\n",
      "1000/1000 [==============================] - 0s 93us/step\n",
      "1000/1000 [==============================] - 0s 70us/step\n",
      "1000/1000 [==============================] - 0s 70us/step\n",
      "1000/1000 [==============================] - 0s 63us/step\n",
      "1000/1000 [==============================] - 0s 62us/step\n",
      "1000/1000 [==============================] - 0s 75us/step\n",
      "1000/1000 [==============================] - 0s 71us/step\n",
      "1000/1000 [==============================] - 0s 73us/step\n",
      "1000/1000 [==============================] - 0s 77us/step\n",
      "1000/1000 [==============================] - 0s 82us/step\n",
      "1000/1000 [==============================] - 0s 85us/step\n",
      "1000/1000 [==============================] - 0s 85us/step\n",
      "1000/1000 [==============================] - 0s 93us/step\n",
      "1000/1000 [==============================] - 0s 90us/step\n",
      "1\n",
      "1000/1000 [==============================] - 0s 91us/step\n",
      "1000/1000 [==============================] - 0s 85us/step\n",
      "1000/1000 [==============================] - 0s 86us/step\n",
      "1000/1000 [==============================] - 0s 99us/step\n",
      "1000/1000 [==============================] - 0s 147us/step\n",
      "1000/1000 [==============================] - 0s 111us/step\n",
      "1000/1000 [==============================] - 0s 129us/step\n",
      "1000/1000 [==============================] - 0s 127us/step\n",
      "1000/1000 [==============================] - 0s 126us/step\n",
      "1000/1000 [==============================] - 0s 130us/step\n",
      "1000/1000 [==============================] - 0s 122us/step\n",
      "1000/1000 [==============================] - 0s 136us/step\n",
      "1000/1000 [==============================] - 0s 145us/step\n",
      "1000/1000 [==============================] - 0s 194us/step\n",
      "1000/1000 [==============================] - 0s 216us/step\n",
      "1000/1000 [==============================] - 0s 359us/step\n",
      "1000/1000 [==============================] - 0s 230us/step\n",
      "1000/1000 [==============================] - 0s 235us/step\n",
      "1000/1000 [==============================] - 0s 324us/step\n",
      "1000/1000 [==============================] - 0s 269us/step\n",
      "1000/1000 [==============================] - 0s 226us/step\n",
      "1000/1000 [==============================] - 0s 236us/step\n",
      "1000/1000 [==============================] - 0s 292us/step\n",
      "1000/1000 [==============================] - 0s 282us/step\n",
      "1000/1000 [==============================] - 0s 330us/step\n",
      "1000/1000 [==============================] - 0s 320us/step\n",
      "1000/1000 [==============================] - 0s 332us/step\n",
      "1000/1000 [==============================] - 0s 311us/step\n",
      "1000/1000 [==============================] - 0s 294us/step\n",
      "1000/1000 [==============================] - 0s 294us/step\n",
      "2\n",
      "1000/1000 [==============================] - 0s 301us/step\n",
      "1000/1000 [==============================] - 0s 339us/step\n",
      "1000/1000 [==============================] - 0s 343us/step\n",
      "1000/1000 [==============================] - 0s 325us/step\n",
      "1000/1000 [==============================] - 0s 327us/step\n",
      "1000/1000 [==============================] - 0s 304us/step\n",
      "1000/1000 [==============================] - 0s 331us/step\n",
      "1000/1000 [==============================] - 0s 319us/step\n",
      "1000/1000 [==============================] - 0s 357us/step\n",
      "1000/1000 [==============================] - 0s 311us/step\n",
      "1000/1000 [==============================] - 0s 354us/step\n",
      "1000/1000 [==============================] - 0s 338us/step\n",
      "1000/1000 [==============================] - 0s 367us/step\n",
      "1000/1000 [==============================] - 0s 378us/step\n",
      "1000/1000 [==============================] - 0s 385us/step\n",
      "1000/1000 [==============================] - 0s 360us/step\n",
      "1000/1000 [==============================] - 0s 366us/step\n",
      "1000/1000 [==============================] - 0s 414us/step\n",
      "1000/1000 [==============================] - 0s 407us/step\n",
      "1000/1000 [==============================] - 0s 374us/step\n",
      "1000/1000 [==============================] - 0s 432us/step\n",
      "1000/1000 [==============================] - 0s 419us/step\n",
      "1000/1000 [==============================] - 0s 442us/step\n",
      "1000/1000 [==============================] - 0s 462us/step\n",
      "1000/1000 [==============================] - 0s 484us/step\n",
      "1000/1000 [==============================] - 0s 415us/step\n",
      "1000/1000 [==============================] - 0s 421us/step\n",
      "1000/1000 [==============================] - 0s 466us/step\n",
      "1000/1000 [==============================] - 0s 434us/step\n",
      "1000/1000 [==============================] - 0s 485us/step\n",
      "3\n",
      "1000/1000 [==============================] - 0s 480us/step\n",
      "1000/1000 [==============================] - 0s 460us/step\n",
      "1000/1000 [==============================] - 1s 517us/step\n",
      "1000/1000 [==============================] - 1s 523us/step\n",
      "1000/1000 [==============================] - 0s 455us/step\n",
      "1000/1000 [==============================] - 1s 519us/step\n",
      "1000/1000 [==============================] - 0s 480us/step\n",
      "1000/1000 [==============================] - 1s 530us/step\n",
      "1000/1000 [==============================] - 1s 580us/step\n",
      "1000/1000 [==============================] - 1s 551us/step\n",
      "1000/1000 [==============================] - 1s 525us/step\n",
      "1000/1000 [==============================] - 1s 603us/step\n",
      "1000/1000 [==============================] - 1s 579us/step\n",
      "1000/1000 [==============================] - 1s 576us/step\n",
      "1000/1000 [==============================] - 1s 639us/step\n",
      "1000/1000 [==============================] - 1s 608us/step\n",
      "1000/1000 [==============================] - 1s 647us/step\n",
      "1000/1000 [==============================] - 1s 644us/step\n",
      "1000/1000 [==============================] - 1s 683us/step\n",
      "1000/1000 [==============================] - 1s 590us/step\n",
      "1000/1000 [==============================] - 1s 701us/step\n",
      "1000/1000 [==============================] - 1s 624us/step\n",
      "1000/1000 [==============================] - 1s 648us/step\n",
      "1000/1000 [==============================] - 1s 701us/step\n",
      "1000/1000 [==============================] - 1s 656us/step\n",
      "1000/1000 [==============================] - 1s 750us/step\n",
      "1000/1000 [==============================] - 1s 748us/step\n",
      "1000/1000 [==============================] - 1s 731us/step\n",
      "1000/1000 [==============================] - 1s 698us/step\n",
      "1000/1000 [==============================] - 1s 803us/step\n",
      "4\n",
      "1000/1000 [==============================] - 1s 731us/step\n",
      "1000/1000 [==============================] - 1s 795us/step\n",
      "1000/1000 [==============================] - 1s 715us/step\n",
      "1000/1000 [==============================] - 1s 754us/step\n",
      "1000/1000 [==============================] - 1s 738us/step\n",
      "1000/1000 [==============================] - 1s 848us/step\n",
      "1000/1000 [==============================] - 1s 815us/step\n",
      "1000/1000 [==============================] - 1s 789us/step\n",
      "1000/1000 [==============================] - 1s 849us/step\n",
      "1000/1000 [==============================] - 1s 778us/step\n",
      "1000/1000 [==============================] - 1s 853us/step\n",
      "1000/1000 [==============================] - 1s 888us/step\n",
      "1000/1000 [==============================] - 1s 820us/step\n",
      "1000/1000 [==============================] - 1s 815us/step\n",
      "1000/1000 [==============================] - 1s 907us/step\n",
      "1000/1000 [==============================] - 1s 911us/step\n",
      "1000/1000 [==============================] - 1s 909us/step\n",
      "1000/1000 [==============================] - 1s 965us/step\n",
      "1000/1000 [==============================] - 1s 941us/step\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1000/1000 [==============================] - 1s 839us/step\n",
      "1000/1000 [==============================] - 1s 837us/step\n",
      "1000/1000 [==============================] - 1s 948us/step\n",
      "1000/1000 [==============================] - 1s 957us/step\n",
      "1000/1000 [==============================] - 1s 878us/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "5\n",
      "1000/1000 [==============================] - 1s 936us/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 2s 2ms/step\n",
      "1000/1000 [==============================] - 2s 2ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 2s 2ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 2s 2ms/step\n",
      "1000/1000 [==============================] - 2s 2ms/step\n",
      "1000/1000 [==============================] - 3s 3ms/step\n",
      "1000/1000 [==============================] - 2s 2ms/step\n",
      "1000/1000 [==============================] - 2s 2ms/step\n",
      "1000/1000 [==============================] - 3s 3ms/step\n",
      "1000/1000 [==============================] - 2s 2ms/step\n",
      "1000/1000 [==============================] - 3s 3ms/step\n",
      "1000/1000 [==============================] - 3s 3ms/step\n",
      "1000/1000 [==============================] - 3s 3ms/step\n",
      "1000/1000 [==============================] - 3s 3ms/step\n",
      "1000/1000 [==============================] - 2s 2ms/step\n",
      "6\n",
      "1000/1000 [==============================] - 3s 3ms/step\n",
      "1000/1000 [==============================] - 2s 2ms/step\n",
      "1000/1000 [==============================] - 3s 3ms/step\n",
      "1000/1000 [==============================] - 1s 916us/step\n",
      "1000/1000 [==============================] - 1s 952us/step\n",
      "1000/1000 [==============================] - 1s 961us/step\n",
      "1000/1000 [==============================] - 1s 997us/step\n",
      "1000/1000 [==============================] - 1s 959us/step\n",
      "1000/1000 [==============================] - 1s 994us/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 954us/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 937us/step\n",
      "1000/1000 [==============================] - 1s 951us/step\n",
      "1000/1000 [==============================] - 1s 947us/step\n",
      "1000/1000 [==============================] - 1s 957us/step\n",
      "1000/1000 [==============================] - 1s 960us/step\n",
      "1000/1000 [==============================] - 1s 958us/step\n",
      "1000/1000 [==============================] - 1s 963us/step\n",
      "1000/1000 [==============================] - 1s 965us/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 986us/step\n",
      "1000/1000 [==============================] - 1s 996us/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "7\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - ETA:  - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "1000/1000 [==============================] - 1s 1ms/step\n",
      "8\n",
      "1000/1000 [==============================] - 1s 1ms/step\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "ERROR:root:Internal Python error in the inspect module.\n",
      "Below is the traceback from this internal error.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Traceback (most recent call last):\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\IPython\\core\\interactiveshell.py\", line 2963, in run_code\n",
      "    exec(code_obj, self.user_global_ns, self.user_ns)\n",
      "  File \"<ipython-input-6-86f3073b978b>\", line 13, in <module>\n",
      "    fmin(f_NN1, space, algo=tpe.suggest, max_evals=try_num1, trials=trials)\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\hyperopt\\fmin.py\", line 307, in fmin\n",
      "    return_argmin=return_argmin,\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\hyperopt\\base.py\", line 635, in fmin\n",
      "    return_argmin=return_argmin)\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\hyperopt\\fmin.py\", line 320, in fmin\n",
      "    rval.exhaust()\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\hyperopt\\fmin.py\", line 199, in exhaust\n",
      "    self.run(self.max_evals - n_done, block_until_done=self.async)\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\hyperopt\\fmin.py\", line 173, in run\n",
      "    self.serial_evaluate()\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\hyperopt\\fmin.py\", line 92, in serial_evaluate\n",
      "    result = self.domain.evaluate(spec, ctrl)\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\hyperopt\\base.py\", line 840, in evaluate\n",
      "    rval = self.fn(pyll_rval)\n",
      "  File \"<ipython-input-5-bf349e57e68b>\", line 38, in f_NN1\n",
      "    shuffle=False)\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\keras\\engine\\training.py\", line 1037, in fit\n",
      "    validation_steps=validation_steps)\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\keras\\engine\\training_arrays.py\", line 217, in fit_loop\n",
      "    callbacks.on_epoch_end(epoch, epoch_logs)\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\keras\\callbacks.py\", line 77, in on_epoch_end\n",
      "    callback.on_epoch_end(epoch, logs)\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\keras\\callbacks.py\", line 444, in on_epoch_end\n",
      "    self.model.save(filepath, overwrite=True)\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\keras\\engine\\network.py\", line 1085, in save\n",
      "    save_model(self, filepath, overwrite, include_optimizer)\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\keras\\engine\\saving.py\", line 121, in save_model\n",
      "    save_weights_to_hdf5_group(model_weights_group, model_layers)\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\keras\\engine\\saving.py\", line 448, in save_weights_to_hdf5_group\n",
      "    weight_values = K.batch_get_value(symbolic_weights)\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\keras\\backend\\tensorflow_backend.py\", line 2390, in batch_get_value\n",
      "    return get_session().run(ops)\n",
      "  File \"C:\\Users\\Administrator\\AppData\\Roaming\\Python\\Python36\\site-packages\\tensorflow\\python\\client\\session.py\", line 877, in run\n",
      "    run_metadata_ptr)\n",
      "  File \"C:\\Users\\Administrator\\AppData\\Roaming\\Python\\Python36\\site-packages\\tensorflow\\python\\client\\session.py\", line 1100, in _run\n",
      "    feed_dict_tensor, options, run_metadata)\n",
      "  File \"C:\\Users\\Administrator\\AppData\\Roaming\\Python\\Python36\\site-packages\\tensorflow\\python\\client\\session.py\", line 1272, in _do_run\n",
      "    run_metadata)\n",
      "  File \"C:\\Users\\Administrator\\AppData\\Roaming\\Python\\Python36\\site-packages\\tensorflow\\python\\client\\session.py\", line 1278, in _do_call\n",
      "    return fn(*args)\n",
      "  File \"C:\\Users\\Administrator\\AppData\\Roaming\\Python\\Python36\\site-packages\\tensorflow\\python\\client\\session.py\", line 1263, in _run_fn\n",
      "    options, feed_dict, fetch_list, target_list, run_metadata)\n",
      "  File \"C:\\Users\\Administrator\\AppData\\Roaming\\Python\\Python36\\site-packages\\tensorflow\\python\\client\\session.py\", line 1350, in _call_tf_sessionrun\n",
      "    run_metadata)\n",
      "KeyboardInterrupt\n",
      "\n",
      "During handling of the above exception, another exception occurred:\n",
      "\n",
      "Traceback (most recent call last):\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\IPython\\core\\interactiveshell.py\", line 1863, in showtraceback\n",
      "    stb = value._render_traceback_()\n",
      "AttributeError: 'KeyboardInterrupt' object has no attribute '_render_traceback_'\n",
      "\n",
      "During handling of the above exception, another exception occurred:\n",
      "\n",
      "Traceback (most recent call last):\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\IPython\\core\\ultratb.py\", line 1095, in get_records\n",
      "    return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\IPython\\core\\ultratb.py\", line 311, in wrapped\n",
      "    return f(*args, **kwargs)\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\IPython\\core\\ultratb.py\", line 345, in _fixed_getinnerframes\n",
      "    records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))\n",
      "  File \"F:\\anaconda\\lib\\inspect.py\", line 1483, in getinnerframes\n",
      "    frameinfo = (tb.tb_frame,) + getframeinfo(tb, context)\n",
      "  File \"F:\\anaconda\\lib\\inspect.py\", line 1441, in getframeinfo\n",
      "    filename = getsourcefile(frame) or getfile(frame)\n",
      "  File \"F:\\anaconda\\lib\\inspect.py\", line 696, in getsourcefile\n",
      "    if getattr(getmodule(object, filename), '__loader__', None) is not None:\n",
      "  File \"F:\\anaconda\\lib\\inspect.py\", line 732, in getmodule\n",
      "    for modname, module in list(sys.modules.items()):\n",
      "KeyboardInterrupt\n"
     ]
    },
    {
     "ename": "KeyboardInterrupt",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "ERROR:tornado.general:Uncaught exception in ZMQStream callback\n",
      "Traceback (most recent call last):\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\zmq\\eventloop\\zmqstream.py\", line 432, in _run_callback\n",
      "    callback(*args, **kwargs)\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\tornado\\stack_context.py\", line 276, in null_wrapper\n",
      "    return fn(*args, **kwargs)\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\ipykernel\\kernelbase.py\", line 283, in dispatcher\n",
      "    return self.dispatch_shell(stream, msg)\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\ipykernel\\kernelbase.py\", line 233, in dispatch_shell\n",
      "    handler(stream, idents, msg)\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\ipykernel\\kernelbase.py\", line 421, in execute_request\n",
      "    self._abort_queues()\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\ipykernel\\kernelbase.py\", line 636, in _abort_queues\n",
      "    self._abort_queue(stream)\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\ipykernel\\kernelbase.py\", line 661, in _abort_queue\n",
      "    poller.poll(50)\n",
      "  File \"F:\\anaconda\\lib\\site-packages\\zmq\\sugar\\poll.py\", line 99, in poll\n",
      "    return zmq_poll(self.sockets, timeout=timeout)\n",
      "  File \"zmq/backend/cython/_poll.pyx\", line 123, in zmq.backend.cython._poll.zmq_poll\n",
      "  File \"zmq/backend/cython/checkrc.pxd\", line 12, in zmq.backend.cython.checkrc._check_rc\n",
      "KeyboardInterrupt\n"
     ]
    }
   ],
   "source": [
    "## set params random search time,when set 50,something will be wrong\n",
    "try_num1 = int(30)\n",
    "Y_pre_list_final= []\n",
    "test_performance_score_list = []\n",
    "\n",
    "for i in range(30):\n",
    "    print(i)\n",
    "    #split data\n",
    "    X_traindata, Y_traindata, X_vdata, Y_vdata, X_testdata, Y_testdata = creat_data(num=i)\n",
    "    #define NN1\n",
    "\n",
    "    trials = Trials()\n",
    "    fmin(f_NN1, space, algo=tpe.suggest, max_evals=try_num1, trials=trials)\n",
    "\n",
    "    loss_list = trials.losses()\n",
    "    min_loss = min(loss_list)\n",
    "    for k in range(try_num1):\n",
    "        if min_loss == loss_list[k]:\n",
    "            key = k\n",
    "    best_results = trials.results[key]\n",
    "    \n",
    "    Y_pre_list_final= Y_pre_list_final + best_results['y_pre_list']\n",
    "    \n",
    "    test_performance_score_list.append(best_results['test_score'])\n",
    "    \n",
    "    final_model =  best_results['models']\n",
    "    final_model.save(Path + '\\\\model\\\\NN1\\\\'+ str(i+1988)+'_Model_NN1_Top1000_Prediction.h5')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-01T07:36:46.629031Z",
     "start_time": "2018-09-01T07:36:46.608976Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[23.848]"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# save out my result\n",
    "print('Model Performance by Average:',np.mean(test_performance_score_list))\n",
    "\n",
    "y_real = np.array(top_1000_data_Y.loc['1988':])\n",
    "print('Model Performance:',Evaluation_fun(Y_pre_list_final, y_real))\n",
    "\n",
    "file = open(Path + '\\\\output\\\\data\\\\Model_NN1_Top1000_Prediction.pkl', 'wb')\n",
    "pickle.dump(Y_pre_list_final, file)\n",
    "file.close()\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  },
  "latex_envs": {
   "LaTeX_envs_menu_present": true,
   "autoclose": false,
   "autocomplete": true,
   "bibliofile": "biblio.bib",
   "cite_by": "apalike",
   "current_citInitial": 1,
   "eqLabelWithNumbers": true,
   "eqNumInitial": 1,
   "hotkeys": {
    "equation": "Ctrl-E",
    "itemize": "Ctrl-I"
   },
   "labels_anchors": false,
   "latex_user_defs": false,
   "report_style_numbering": false,
   "user_envs_cfg": false
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
